<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app" :hoverable="true">
      <a-row justify="space-between" style="margin-bottom: 20px">
        <a-col :span="12">
          <a-space :size="20">
            <h3 style="display: inline">文档编号：{{ data.form.docEntry || '无' }}</h3>
            <h3 style="display: inline">名称：{{ data.form.name || '无' }}</h3>
          </a-space>
        </a-col>

        <a-col :span="12">
          <a-row justify="end">
            <a-button-group>
              <a-button @click="back()">
                <ArrowLeftOutlined />
                返回
              </a-button>
              <a-button @click="save()" v-if="!(data.form.docStatus === 'C' || !data.form.edit)">
                <CheckCircleOutlined />
                保 存
              </a-button>
              <a-button
                v-privilege="'file:docment:edit'"
                @click="edit()"
                v-if="!(data.form.docStatus === 'C' || data.form.edit || data.form.docStatus === 'L')"
              >
                <FormOutlined />
                编 辑
              </a-button>
              <a-button
                v-privilege="'file:docment:del'"
                @click="del()"
                v-if="!(data.form.edit || data.form.docStatus === 'L' || data.form.approved)"
              >
                <DeleteOutlined />
                删 除
              </a-button>
              <a-button
                v-privilege="'file:docment:approvedview'"
                @click="approved()"
                v-if="!data.form.edit"
              >
                <EyeOutlined />
                审核
              </a-button>

              <a-dropdown v-if="!(data.form.edit || data.form.docStatus === 'L')">
                <a-button v-privilege="'file:docment:more'">
                  <MoreOutlined />
                  更多
                </a-button>
                <template #overlay>
                  <a-menu @click="more">
                    <a-menu-item key="a" v-if="data.form.docStatus !== 'C'">关闭</a-menu-item>
                    <a-menu-item key="b" v-if="data.form.docStatus === 'C'">打开</a-menu-item>
                    <a-menu-item key="c">上传审核</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="refresh">
                <RedoOutlined />
                刷 新
              </a-button>
            </a-button-group>
          </a-row>
        </a-col>
      </a-row>

      <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 5 }">
        <a-row class="smart-query-form-row">
          <a-col :span="6">
            <a-form-item label="文件名称" name="name">
              <a-input v-if="data.form.edit" v-model:value="data.form.name" placeholder="请输入文件名称" />
              <span v-else>{{ data.form.name || '未设置' }}</span>
            </a-form-item>
            <a-form-item label="文件类型" name="typeId">
              <FiletypeTreeSelect
                v-if="data.form.edit"
                key="docEntry"
                v-model:value="data.form.typeId"
                @change="changeHandle"
                placeholder="请选择文件类型"
              />
              <span v-else>{{ data.form.typeName || '未选择' }}</span>
            </a-form-item>
            <a-form-item label="公开文件" name="docPrivate">
              <a-radio-group v-if="data.form.edit" v-model:value="data.form.docPrivate">
                <a-radio value="A">公开</a-radio>
                <a-radio value="B">私密</a-radio>
              </a-radio-group>
              <span v-else>
                <a-tag v-if="data.form.docPrivate === 'A'" color="#87d068">公开 </a-tag>
                <a-tag v-if="data.form.docPrivate === 'B'" color="#f50">私密 </a-tag>
                <span v-if="!data.form.docPrivate">未设置</span>
              </span>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="备注">
              <a-textarea
                v-if="data.form.edit"
                v-model:value="data.form.remark"
                :rows="2"
                placeholder="请输入备注信息"
              />
              <span v-else>{{ data.form.remark || '无' }}</span>
            </a-form-item>
            <a-form-item label="制单">
              <span>{{ (data.form.createBy || '未知') + '&nbsp;&nbsp;' + (data.form.createTime || '无') }}</span>
            </a-form-item>
            <a-form-item label="修改">
              <span>{{ (data.form.updateBy || '未知') + '&nbsp;&nbsp;' + (data.form.updateTime || '无') }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8"></a-col>
        </a-row>
      </a-form>

      <a-row>
        <a-tabs v-model:activeKey="data.activeKey" style="width: 100%">
          <a-tab-pane key="1" tab="版本">
            <a-row>
              <a-button-group>
                <a-button
                  v-if="data.form.docEntry"
                  v-privilege="'file:docment:import'"
                  :disabled="data.form.docStatus === 'L'"
                  @click="lineaImportFile"
                  type="link"
                >
                  <template #icon><ImportOutlined /></template>
                  上传文件
                </a-button>
              </a-button-group>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-table
                  row-key="lineNum"
                  :columns="columnsa"
                  :data-source="data.form.lista"
                  :scroll="{ x: 600, y: 500 }"
                  :pagination="{
                    showSizeChanger: true,
                    showQuickJumper: true,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100', '200'],
                  }"
                >
                  <template #bodyCell="{ text, record, column, index }">
                    <template v-if="column.dataIndex === 'docSize'">
                      <span> {{ getFileSize(text) }}</span>
                    </template>
                    <template v-if="column.dataIndex === 'approved'">
                      <span> {{ text ? '已审核' : '未审核' }}</span>
                    </template>
                    <template v-if="column.dataIndex === 'printApprov'">
                      <span> {{ text ? '已审核' : '未审核' }}</span>
                    </template>
                    <template v-if="column.dataIndex === 'recycleApprov'">
                      <span> {{ text ? '已审核' : '未审核' }}</span>
                    </template>

                    <template v-if="column.dataIndex === 'action'">
                      <a-button-group>
                        <a-button
                          v-privilege="'file:docment:printexcute'"
                          v-if="index === 0 && record.approved && record.printApprov"
                          @click="print(record)"
                          type="link"
                        >
                          <template #icon><PrinterOutlined /></template>
                          打印
                        </a-button>
                        <a-button
                          v-privilege="'file:docment:print'"
                          v-if="index === 0 && record.approved && !record.printApprov && data.form.docStatus !== 'L'"
                          @click="PrintApply(record)"
                          type="link"
                        >
                          <template #icon><PrinterOutlined /></template>
                          打印申请
                        </a-button>
                        <a-button
                          v-privilege="'file:docment:recycle'"
                          v-if="index === 0 && record.approved && !record.printApprov && data.form.docStatus !== 'L'"
                          @click="recycleApply(record)"
                          type="link"
                        >
                          <template #icon><ClearOutlined /></template>
                          回收申请
                        </a-button>
                        <a-button
                          v-privilege="'file:docment:view'"
                          v-if="index === 0"
                          @click="onPdfViewHandle(record)"
                          type="link"
                        >
                          <template #icon><EyeOutlined /></template>
                          预览
                        </a-button>
                        <a-button
                          v-privilege="'file:docment:historyview'"
                          v-if="index !== 0"
                          @click="onPdfViewHandle(record)"
                          type="link"
                        >
                          <template #icon><EyeOutlined /></template>
                          预览
                        </a-button>
                      </a-button-group>
                    </template>
                  </template>
                </a-table>
              </a-col>
            </a-row>
          </a-tab-pane>

          <!-- 人员标签页：新增批量删除功能 -->
          <a-tab-pane key="2" tab="人员">
            <a-row style="margin-bottom: 16px">
              <a-button-group>
                <!-- 原有选择开通按钮 -->
                <a-button
                  v-if="data.form.docEntry"
                  v-privilege="'file:docment:open'"
                  :disabled="data.form.docStatus === 'L'"
                  @click="addRoleEmployee"
                  type="link"
                >
                  <template #icon><ImportOutlined /></template>
                  选择开通
                </a-button>

                <!-- 新增批量删除按钮 -->
                <a-button
                  v-privilege="'file:docment:batchDelPerson'"
                  :disabled="!selectedPersonKeys.length || data.form.docStatus === 'L'"
                  @click="batchDeletePersons"
                  type="link"
                  danger
                >
                  <template #icon><DeleteOutlined /></template>
                  批量移除
                </a-button>
              </a-button-group>
            </a-row>
            <a-col :span="24">
              <a-table
                row-key="lineNum"
                :columns="columnsb"
                :data-source="data.form.listb"
                :scroll="{ x: 600, y: 500 }"
                :pagination="{
                  showSizeChanger: true,
                  showQuickJumper: true,
                  defaultPageSize: 20,
                  pageSizeOptions: ['20', '50', '100', '200'],
                }"
              :row-selection="{
              type: 'checkbox',
              selectedRowKeys: selectedPersonKeys,
              onChange: handlePersonSelectChange,
              getCheckboxProps: (record) => ({
              disabled: data.form.docStatus === 'L' // 状态为L时禁用选择
              })
              }"
              >
              <template #bodyCell="{ text, record, column, index }">
                <template v-if="column.dataIndex === 'action'">
                  <a-button-group>
                    <a-button
                      @click="linebDel(record)"
                      type="link"
                      danger
                      :disabled="data.form.docStatus === 'L'"
                    >
                      移除
                    </a-button>
                  </a-button-group>
                </template>
              </template>
              </a-table>
            </a-col>
          </a-tab-pane>

          <a-tab-pane key="3" tab="打印">
            <a-table
              row-key="lineNum"
              :header-height="30"
              :columns="columnsaa"
              :data-source="data.form.listaa"
              :scroll="{ x: 600, y: 500 }"
              :pagination="{
                showSizeChanger: true,
                showQuickJumper: true,
                defaultPageSize: 20,
                pageSizeOptions: ['20', '50', '100', '200'],
              }"
            >
              <template #bodyCell="{ text, record, column, index }">
                <template v-if="column.dataIndex === 'approved'">
                  <span> {{ text ? '已审核' : '未审核' }}</span>
                </template>
              </template>
            </a-table>
          </a-tab-pane>

          <a-tab-pane key="4" tab="回收">
            <a-table
              row-key="lineNum"
              :header-height="30"
              :columns="columnsab"
              :data-source="data.form.listab"
              :scroll="{ x: 600, y: 500 }"
              :pagination="{
                showSizeChanger: true,
                showQuickJumper: true,
                defaultPageSize: 20,
                pageSizeOptions: ['20', '50', '100', '200'],
              }"
            >
              <template #bodyCell="{ text, record, column, index }">
                <template v-if="column.dataIndex === 'approved'">
                  <span> {{ text ? '已审核' : '未审核' }}</span>
                </template>
                <template v-if="column.dataIndex === 'docmentSrc'"></template>
              </template>
              <template #expandedRowRender="{ record }">
                <a-image :width="200" :src="record.docmentSrc" />
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-row>
    </a-card>
  </a-spin>

  <a-modal draggable="true" v-model:open="data.uploadModalFlag" title="上传文件">
    <FileUpload
      list-type="text"
      accept=".pdf"
      :maxUploadSize="1"
      buttonText="点击上传文件"
      :defaultFileList="[]"
      :multiple="true"
      :folder="FILE_FOLDER_TYPE_ENUM.COMMON.value"
      @change="success"
    />
  </a-modal>

  <Approve :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approve>

  <EmployeeTableSelectModal ref="selectEmployeeModal" @selectData="selectData" />

  <a-drawer v-model:open="data.drawerFlag" width="100%" destroy-on-close>
    <vue-office-pdf :src="data.docUrl" style="height: 90vh" />
  </a-drawer>

  <a-modal width="800px" v-model:open="data.modalFlag" title="打印申请" @ok="onFinish">
    <a-form ref="printApplyFrom" :model="data.formab" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <a-form-item label="打印份数" name="printNum" :rules="[{ required: true, message: '请输入打印份数!' }]">
        <a-input-number min="1" v-model:value="data.formab.printNum" addon-after="份"></a-input-number>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal width="800px" v-model:open="data.modalRecycleFlag" title="回收申请" @ok="onRecycleFinish">
    <a-form ref="recycleFrom" :model="data.formab" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <a-form-item label="回收份数" name="printNum" required>
        <a-input-number min="1" v-model:value="data.formab.printNum" addon-after="份"></a-input-number>
      </a-form-item>

      <a-form-item label="回收资料" name="docmentSrc" required>
        <FileUpload
          list-type="text"
          :maxUploadSize="1"
          buttonText="点击上传文件"
          :defaultFileList="[]"
          :multiple="true"
          :folder="FILE_FOLDER_TYPE_ENUM.COMMON.value"
          @change="RecycleFileImportSuccess"
          accept=".jpg, .png"
        />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal destroyOnClose  :okText="data.printLoading? '打印中':'确认'" :confirmLoading="data.printLoading"  v-model:open="data.modalVisible" title="选择打印机" style="top: 20px" @ok="onPrintOkHandle()">
    <a-form :disabled="data.printLoading" ref="printForm" :model="data.chooseaLine" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <a-form-item label="打印机" name="macName" :rules="[{ required: true, message: '请选择打印机!' }]">
        <a-select ref="select" v-model:value="data.chooseaLine.macName" allow-clear>
          <a-select-option :value="item" v-for="item in data.printList">{{ item }}</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
  import { onMounted, reactive, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { smartSentry } from '/src/lib/smart-sentry';
  import { docmentaApi, docmentApi, docmentaaApi, docmentabApi, docmentbApi } from '/@/api/business/file/docment-api.js';
  import FiletypeTreeSelect from '/@/views/business/file/filetypeData/components/filetype-tree-select.vue';
  import { useRouter, useRoute } from 'vue-router';
  import { FILE_FOLDER_TYPE_ENUM } from '/src/constants/support/file-const.js';
  import FileUpload from '/src/components/support/file-upload/index.vue';
  import { columnsa, columnsb, columnsaa, columnsab } from '/@/views/business/file/docmentData/data.js';
  import Approve from '/@/components/business/file/approve.vue';
  import { approvordApi } from '/@/api/business/file/approvord-api.js';
  import EmployeeTableSelectModal from '/@/components/system/employee-table-select-modal/index.vue';
  import { SmartLoading } from '/@/components/framework/smart-loading/index.js';
  import VueOfficePdf from '@vue-office/pdf';
  // 补充导入删除图标
  import {
    ArrowLeftOutlined,
    CheckCircleOutlined,
    FormOutlined,
    DeleteOutlined,
    EyeOutlined,
    MoreOutlined,
    RedoOutlined,
    ImportOutlined,
    PrinterOutlined,
    ClearOutlined
  } from '@ant-design/icons-vue';

  const route = useRoute();
  const router = useRouter();
  const data = reactive({
    form: {
      docEntry: null,
      objId: null,
      objName: null,
      approved: false,
      docStatus: 'O',
      edit: false,
      typeId: null,
      typeName: null,
      docPrivate: 'A',
      createBy: '',
      createTime: '',
      updateBy: '',
      updateTime: '',
      version: null,
      lista: [],
      listb: [],  // 人员列表数据
      listaa: [],
      listab: [],
    },
    forma: {},
    radioGroup: null,
    rules: {
      name: [{ required: true, message: '请输入文件名称' }],
      typeId: [{ required: true, message: '请选择文件类型' }],
      docPrivate: [{ required: true, message: '请选择公开状态' }],
    },
    model: {
      absId: '',
    },
    editableData: {
      nowDate: null,
    },
    visible: {
      approvord: false,
      user: false,
    },
    approvedData: {
      baseEntry: null,
      tabName: null,
    },
    activeKey: '1',
    uploadModalFlag: false,
    drawerFlag: false,
    modalFlag: false,
    modalRecycleFlag: false,
    modalVisible: false,
    docSrc: '',
    chooseLine: null,
    chooseaLine: null,
    formab: {
      printNum: 1,
      docmentSrc: '',
    },

    formb: {
      ids: [],
      docEntry: null,
      baseVersion: null,
    },

    docUrl: '',
    printList: [],
    printLoading: false,
  });
  const tableLoading = ref(false);
  const formRef = ref(null);

  const recycleFrom = ref(null);
  const selectEmployeeModal = ref();

  // 新增：人员列表多选相关
  const selectedPersonKeys = ref([]); // 选中的行ID集合
  const selectedPersonRecords = ref([]); // 选中的行数据集合

  // 初始化
  function init() {
    if (route.query.type === 'info') {
      data.form.docEntry = route.query.docEntry;
      queryData();
    } else {
      data.form.edit = true;
    }
  }

  // 监听标签页切换，清空选中状态
  watch(
    () => data.activeKey,
    (newKey) => {
      if (newKey !== '2') {
        selectedPersonKeys.value = [];
        selectedPersonRecords.value = [];
      }
    }
  );

  // 更多操作
  function more({ key }) {
    if (key === 'a') {
      data.form.docStatus = 'C';
      tableLoading.value = true;
      docmentApi
        .update(data.form)
        .then((res) => {
          queryData();
        })
        .finally(() => {
          tableLoading.value = false;
        });
    } else if (key === 'b') {
      data.form.docStatus = 'O';
      tableLoading.value = true;
      docmentApi
        .update(data.form)
        .then((res) => {
          queryData();
        })
        .finally(() => {
          tableLoading.value = false;
        });
    } else if (key === 'c') {
      approvordApi
        .add({
          docEntry: 0,
          approvLineNum: 2,
          approvType: 'A',
          baseEntry: data.form.docEntry,
          tabName: data.form.objName,
          docStatus: 'O',
          tabId: data.form.objId,
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    } else if (key === 'd') {
      data.modalFlag = true;
    } else if (key === 'e') {
      data.modalRecycleFlag = true;
    }
  }

  // 增删改查
  function add() {
    data.form;
    data.form.edit = true;
    data.form.lista = [];
    router.push({ path: '/file/docmenta', query: { type: 'new', docEntry: null } });
  }

  function save() {
    formRef.value
      .validate()
      .then(() => {
        tableLoading.value = true;
        if (data.form.docEntry) {
          docmentApi
            .update(data.form)
            .then((res) => {
              queryData(data.form.docEntry);
              message.success('修改成功！');
            })
            .catch((err) => {
              tableLoading.value = false;
            });
        } else {
          docmentApi
            .add(data.form)
            .then((res) => {
              data.form.docEntry = res.data;
              message.success('保存成功！');
              router.push({ path: '/file/docmenta', query: { type: 'info', docEntry: res.data } });
              queryData(res.data);
            })
            .catch((err) => {
              tableLoading.value = false;
            });
        }
      })
      .catch((err) => {
        message.error('页面校验失败！');
      });
  }

  function edit() {
    data.form.edit = true;
    data.form.lista.forEach((item) => {
      item.edit = true;
    });
  }

  function del() {
    Modal.confirm({
      content: `确认删除（${data.form.docEntry}）`,
      onOk() {
        docmentApi.delete(data.form.docEntry).then((res) => {
          message.success('删除成功！');
          back();
        });
      },
      cancelText: '取消',
      onCancel() {
        Modal.destroyAll();
      },
    });
  }

  function queryData() {
    tableLoading.value = true;
    docmentApi
      .info(data.form.docEntry)
      .then((res) => {
        data.form = res.data;
        tableLoading.value = false;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  }

  function refresh() {
    queryData();
  }

  function back() {
    const { listPageNum, listPageSize } = route.query;
    router.push({
      path: '/file/docment',
      query: {
        pageNum: listPageNum,
        pageSize: listPageSize
      }
    });
  }

  // 审核相关
  function approved() {
    data.approvedData.baseEntry = data.form.docEntry;
    data.approvedData.tabName = data.form.objName;
    data.approvedData.title = '24324324';
    data.visible.approvord = true;
  }

  function onclose() {
    data.visible.approvord = false;
    queryData();
  }

  function success(item) {
    docmentaApi
      .add({
        docEntry: data.form.docEntry,
        lineNum: null,
        lineStatus: 'O',
        title: item[0].fileName,
        docKey: item[0].fileKey,
        docUrl: item[0].fileUrl,
        type: item[0].fileType,
        folder: '文件系统',
        docSize: item[0].fileSize,
        baseVersion: data.form.version,
      })
      .then((res) => {
        data.uploadModalFlag = false;
        queryData();
      });
  }

  function changeHandle(item, it) {
    data.form.typeName = it;
  }

  /* 版本相关方法 */
  function onPdfViewHandle(item) {
    const apiUrl = import.meta.env.VITE_APP_API_URL;
    item.docUrl=apiUrl+'/upload/'+item.docKey;
    data.docUrl = item.docUrl ? item.docUrl : item.docmentSrc;
    data.drawerFlag = true;
  }

  const printApplyFrom = ref();
  function onFinish() {
    printApplyFrom.value
      .validate()
      .then((res) => {
        tableLoading.value = true;
        data.modalFlag = false;
        docmentaaApi
          .add({
            docEntry: data.form.docEntry,
            lineNum: null,
            baseNum: data.chooseLine.lineNum,
            printNum: data.formab.printNum,
          })
          .then((res) => {
            approvordApi
              .add({
                docEntry: 0,
                approvLineNum: 2,
                approvType: 'C',
                baseEntry: data.form.docEntry,
                tabName: data.form.objName,
                docStatus: 'O',
                tabId: data.form.objId,
                baseVersion: data.form.version,
              })
              .then((res) => {
                tableLoading.value = false;
                queryData();
              });
          });
      })
      .catch((err) => {});
  }

  function onRecycleFinish() {
    recycleFrom.value
      .validate()
      .then(() => {
        data.modalRecycleFlag = false;
        tableLoading.value = true;
        docmentabApi
          .add({
            docEntry: data.form.docEntry,
            lineNum: null,
            baseNum: data.chooseLine.lineNum,
            printNum: data.formab.printNum,
            docmentSrc: data.formab.docmentSrc,
          })
          .then((res) => {
            approvordApi
              .add({
                docEntry: 0,
                approvLineNum: 2,
                approvType: 'D',
                baseEntry: data.form.docEntry,
                tabName: data.form.objName,
                docStatus: 'O',
                tabId: data.form.objId,
                baseVersion: data.form.version,
              })
              .then((res) => {
                tableLoading.value = false;
                queryData();
              });
          });
      })
      .catch(() => {});
  }

  function PrintApply(item) {
    data.modalFlag = true;
    data.chooseLine = item;
  }

  function recycleApply(item) {
    data.modalRecycleFlag = true;
    data.chooseLine = item;
  }

  function lineaImportFile() {
    if (data.form.lista.length === 0 || data.form.lista[0].recycleNum - data.form.lista[0].printNum >= 0) {
      data.uploadModalFlag = true;
    } else {
      Modal.error({
        title: '错误',
        content: `上传新文件前请先将之前打印 【${data.form.lista[0].title}】 的  【${data.form.lista[0].printNum}】 份文件回收！`,
      });
    }
  }

  function getFileSize(size) {
    if (!size) return '';
    let num = 1024.0;
    if (size < num) return size + 'B';
    if (size < Math.pow(num, 2)) return (size / num).toFixed(2) + 'KB';
    if (size < Math.pow(num, 3)) return (size / Math.pow(num, 2)).toFixed(2) + 'MB';
    if (size < Math.pow(num, 4)) return (size / Math.pow(num, 3)).toFixed(2) + 'G';
    return (size / Math.pow(num, 4)).toFixed(2) + 'T';
  }

  function print(item) {
    data.chooseaLine = item;
    tableLoading.value = true;
    docmentaApi
      .printList()
      .then((res) => {
        data.printList = res.data;
      })
      .finally(() => {
        data.modalVisible = true;
        tableLoading.value = false;
      });
  }

  const printForm = ref();
  function onPrintOkHandle() {
    printForm.value
      .validate()
      .then((res) => {
        data.printLoading = true;
        data.chooseaLine.baseVersion = data.form.version;
        docmentaApi
          .printNoRole(data.chooseaLine)
          .then(() => {})
          .finally(() => {
            queryData();
            data.printLoading = false;
            data.modalVisible = false;
          });
      })
      .catch((err) => {});
  }

  /* 人员列表相关方法 */
  // 单行删除
  function linebDel(record) {
    Modal.confirm({
      content: `确认移除人员【${record.userName || record.lineNum}】?`,
      onOk() {
        docmentbApi.delete(record).then(() => {
          message.success('移除成功');
          queryData();
          // 清除可能的选中状态
          selectedPersonKeys.value = selectedPersonKeys.value.filter(key => key !== record.lineNum);
        });
      }
    });
  }

  // 新增：处理人员选择变化
  function handlePersonSelectChange(selectedKeys, selectedRows) {
    selectedPersonKeys.value = selectedKeys;
    selectedPersonRecords.value = selectedRows;
  }

  // 新增：批量删除人员
  function batchDeletePersons() {
    if (!selectedPersonRecords.value.length) return;

    const names = selectedPersonRecords.value.map(item => item.userName || item.lineNum).join('、');
    Modal.confirm({
      title: '批量删除确认',
      content: `确定要移除选中的【${names}】共${selectedPersonRecords.value.length}名人员吗？`,
      okText: '确认删除',
      okType: 'danger',
      onOk() {
        tableLoading.value = true;
        // 调用批量删除接口（假设后端支持批量删除，参数为选中的lineNum集合）
        docmentbApi.deleteList({
          docEntry: data.form.docEntry,
          lineNums: selectedPersonKeys.value
        }).then(() => {
          message.success(`成功移除${selectedPersonRecords.value.length}名人员`);
          queryData();
          // 清空选中状态
          selectedPersonKeys.value = [];
          selectedPersonRecords.value = [];
        }).finally(() => {
          tableLoading.value = false;
        });
      }
    });
  }

  async function addRoleEmployee() {
    let selectedIdList = data.form.listb.map((e) => e.userId) || [];
    selectEmployeeModal.value.showModal(selectedIdList);
  }

  async function selectData(list) {
    tableLoading.value = true;
    SmartLoading.show();
    try {
      data.formb.ids = list;
      data.formb.docEntry = data.form.docEntry;
      data.formb.baseVersion = data.form.version;

      docmentbApi.batchAdd(data.formb).then((res) => {
        tableLoading.value = false;
        queryData();
      });
      message.success('添加成功');
      await queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  function RecycleFileImportSuccess(item) {
    data.formab.docmentSrc = item[0].fileUrl;
  }

  onMounted(init);
</script>

<style lang="less"></style>
